package com.learn.xueer.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.learn.xueer.R
import com.learn.xueer.app.base.BaseFragment1
import com.learn.xueer.app.ext.init
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.data.model.bean.BannerInfo
import com.learn.xueer.data.model.bean.TextBookResponse
import com.learn.xueer.data.model.bean.TextBookUnitResponse
import com.learn.xueer.databinding.FragmentHomeBinding
import com.learn.xueer.ui.activity.HearActivity
import com.learn.xueer.ui.activity.MessageActivity
import com.learn.xueer.ui.activity.UnitWordsActivity
import com.learn.xueer.ui.activity.WordPkActivity
import com.learn.xueer.ui.adapter.HomeExpandAdapter
import com.learn.xueer.ui.adapter.HomeMenuAdapter
import com.learn.xueer.ui.adapter.UnitPopAdapter
import com.learn.xueer.ui.viewmodel.RequestHomeViewModel
import com.learn.xueer.ui.widgets.WheelView
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.android.synthetic.main.fragment_home.bannerView
import kotlinx.android.synthetic.main.fragment_home.bookInfo
import kotlinx.android.synthetic.main.fragment_home.recyclerViewMenu
import kotlinx.android.synthetic.main.fragment_home.recyclerViewMenu2
import me.hgj.jetpackmvvm.ext.parseState


class HomeFragment : BaseFragment1<RequestHomeViewModel, FragmentHomeBinding>() {

    private val menuAdapter: HomeMenuAdapter by lazy { HomeMenuAdapter(arrayListOf()) }
    private val expandAdapter: HomeExpandAdapter by lazy { HomeExpandAdapter(arrayListOf()) }
    private lateinit var textBook: TextBookResponse
    private var textBookUnit: TextBookUnitResponse? = null
    private lateinit var popupWindow: PopupWindow
    private lateinit var unitPop: PopupWindow
    private lateinit var rvGrade: WheelView
    private lateinit var rvVersion: WheelView
    private val unitAdapter: UnitPopAdapter by lazy { UnitPopAdapter(arrayListOf()) }

    @SuppressLint("MissingInflatedId", "ResourceAsColor")
    override fun initView(savedInstanceState: Bundle?) {
        addLoadingObserve(mViewModel)
        mViewBind.viewmodel = mViewModel
        mViewBind.click = ProxyClick()

        val menuLayoutManager = StaggeredGridLayoutManager(3, RecyclerView.VERTICAL)
        val expandLayoutManager = StaggeredGridLayoutManager(5, RecyclerView.VERTICAL)
        recyclerViewMenu.init(menuLayoutManager, menuAdapter, false)
        recyclerViewMenu2.init(expandLayoutManager, expandAdapter, false)
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            mViewModel.homeResult.value?.let { resultState ->
                parseState(resultState, onSuccess = {
                    it?.let {
                        if (it.jingangqu[position].id == 8) {
                            startActivity(Intent(mActivity, WordPkActivity::class.java))
                        } else {
                            startActivity(Intent(mActivity, HearActivity::class.java))
                        }
                    }
                })
            }
        }

        expandAdapter.setOnItemClickListener { adapter, view, position ->
            startActivity(Intent(mActivity, HearActivity::class.java))
        }

        val inflate = LayoutInflater.from(mActivity)
            .inflate(R.layout.text_book_dialog, null)
        inflate.findViewById<TextView>(R.id.cancel).setOnClickListener {
            popupWindow.dismiss()
        }

        inflate.findViewById<TextView>(R.id.confirm).setOnClickListener {
            textBook = rvVersion.seletedItem
            CacheUtil.setTextBook(textBook)
            mViewModel.textBooksTitle.set(textBook.gradeName + " " + textBook.versionName)
            mViewModel.textBookUnitReq(textBook.versionId.toString())
            popupWindow.dismiss()
        }
        rvGrade = inflate.findViewById<WheelView>(R.id.rvGrade)
        rvVersion = inflate.findViewById<WheelView>(R.id.rvVersion)
        rvVersion.setLevel(1)
//        dialog.setContentView(inflate)

        rvGrade.setOnWheelViewListener { selectedIndex, item ->
            rvVersion.setItems(item.children)
        }

        popupWindow = PopupWindow(inflate, MATCH_PARENT, WRAP_CONTENT)
        // 设置PopupWindow需要获得焦点，否则无法响应点击事件
        // 设置PopupWindow需要获得焦点，否则无法响应点击事件
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(ColorDrawable()) // 必须设置Background才能消失
        popupWindow.setOnDismissListener {
            backgroundAlpha(1f)
        }

        val unitPopView = LayoutInflater.from(mActivity)
            .inflate(R.layout.text_book_unit_dialog, null)
        unitPopView.findViewById<TextView>(R.id.btnFinish).setOnClickListener {
            unitPop.dismiss()
        }
        val rvUnit = unitPopView.findViewById<RecyclerView>(R.id.rvUnit)
        unitPop = PopupWindow(unitPopView, MATCH_PARENT, WRAP_CONTENT)
        // 设置PopupWindow需要获得焦点，否则无法响应点击事件
        // 设置PopupWindow需要获得焦点，否则无法响应点击事件
        unitPop.isFocusable = true
        unitPop.setBackgroundDrawable(ColorDrawable()) // 必须设置Background才能消失
        unitPop.setOnDismissListener {
            backgroundAlpha(1f)
        }
        rvUnit.init(LinearLayoutManager(mActivity), unitAdapter)
        unitAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            textBookUnit = unitAdapter.data[i]
            mViewModel.textBooksDesc.set(unitAdapter.data[i].name)
            val intent = Intent(mActivity, UnitWordsActivity::class.java)
            intent.putExtra("id", unitAdapter.data[i].unitid)
            intent.putExtra("title", unitAdapter.data[i].name)
            startActivity(intent)
            unitPop.dismiss()
        }

    }

    override fun lazyLoadData() {
        mViewModel.homeInfoReq()
        mViewModel.textBookReq()
    }

    override fun createObserver() {
        mViewModel.homeResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                val banner = it?.banner
                val jingangqu = it?.jingangqu
                val kewaikuozhan = it?.kewaikuozhan
                menuAdapter.setList(jingangqu)
                expandAdapter.setList(kewaikuozhan)
                val jiaocai = it?.jiaocai
                bannerView.adapter = object : BannerImageAdapter<BannerInfo>(it?.banner) {
                    override fun onBindView(
                        holder: BannerImageHolder?,
                        data: BannerInfo?,
                        position: Int,
                        size: Int
                    ) {
                        holder?.let {
                            holder.imageView.scaleType = ImageView.ScaleType.FIT_XY
                            holder.imageView.adjustViewBounds = true

                            val bitmapTransform =
                                RequestOptions.bitmapTransform(RoundedCorners(SizeUtils.dp2px(15F)))

                            Glide.with(holder.itemView)
                                .load(data?.image)
                                .apply(bitmapTransform)
                                .into(holder.imageView)
                        }
                    }
                }
                bannerView.apply {

                    // 添加生命周期管理，确保在适当的生命周期内开始和停止轮播
                    addBannerLifecycleObserver(this@HomeFragment)
                    setLoopTime(3000)
                    setIndicatorHeight(0)
                    setIndicatorWidth(0, 0)
                }
                if (jiaocai != null || !jiaocai?.isEmpty()!!) {
                    val textBooks = jiaocai.first().text_books
                }
                bannerView.start()
            }, {})
        })

        mViewModel.textBookResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                it?.reverse()
                if (CacheUtil.getTextBook() == null) {
                    textBook = it?.first()?.children?.first()!!
                    CacheUtil.setTextBook(it.first().children.first())
                } else {
                    textBook = CacheUtil.getTextBook()!!
                }
                mViewModel.textBooksTitle.set(textBook.gradeName + " " + textBook.versionName)
                mViewModel.textBookUnitReq(textBook.versionId.toString())
                rvGrade.setItems(it)
                rvVersion.setItems(it?.get(rvGrade.seletedIndex)?.children ?: arrayListOf())
            }, {})
        })

        mViewModel.textBookUnitResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                if (it?.isNotEmpty()!!) {
                    textBookUnit = it.first()
                    mViewModel.textBooksDesc.set(it.first().name)
                } else {
                    mViewModel.textBooksDesc.set(textBook.gradeName + " " + textBook.versionName)
                }
                unitAdapter.setList(it)
            }, {})
        })
    }

    inner class ProxyClick {

        fun cutTextBook() {
//           dialog.show()
            popupWindow.showAtLocation(bookInfo, Gravity.BOTTOM, 0, 0)
            backgroundAlpha(0.8f)
        }

        fun message() {
            startActivity(Intent(mActivity, MessageActivity::class.java))
        }

        fun selectUnit() {
            unitPop.showAtLocation(bookInfo, Gravity.BOTTOM, 0, 0)
            backgroundAlpha(0.8f)
        }

        fun jumpToUnit() {
            if (textBookUnit == null) {
                Toast.makeText(mActivity, "单元为空", Toast.LENGTH_SHORT).show()
                return
            }
            val intent = Intent(mActivity, UnitWordsActivity::class.java)
            intent.putExtra("id", textBookUnit?.unitid)
            intent.putExtra("title", textBookUnit?.name)
            startActivity(intent)
        }
    }

    private fun backgroundAlpha(f: Float) {//透明函数
        val lp = mActivity.window.attributes;
        lp.alpha = f;
        mActivity.window.setAttributes(lp);
    }
}